﻿using AngleSharp.Dom;
using AngleSharp.Parser.Html;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Threading.Tasks;

namespace BaseEpub
{
    public class ReplacePageImg:NcxBase
    {
        public override void GetContent(string ncxPath)
        {
            throw new NotImplementedException();
        }
        HtmlParser parser = new HtmlParser();
        public override void ReplaceImg(string content)
        {
            //获取正文里的正文dom
            //<img src="../Images/gs020.jpg" class="inline-image2"/></p>
            var doc = parser.Parse(content);
            IEnumerable<IElement> imgEleList = doc.QuerySelectorAll("img"); //Distinct去掉重复的图片数据
            if (imgEleList != null && imgEleList.Count() > 0)
            {
                //判断图片路径是否已经存在，存在就不再导入
                string isExistSrc = "";
                foreach (IElement imgEle in imgEleList)
                {
                    string src = imgEle.GetAttribute("src");
                    if (!string.IsNullOrEmpty(isExistSrc) && src == isExistSrc)
                    {
                        continue;
                    }
                    isExistSrc = src;

                    string[] srcStr = src.Split('/');
                    string imgPath = @"E:\MyCode\NetCode\AngleSharpDemo\有机化学样本3\有机化学样本3\OEBPS\" + srcStr[1] + @"\" + srcStr[2];
                    byte[] imgBytes = GetByte(imgPath);
                    string imgType = ImageTypeCheck.CheckImageTypeName(imgPath);
                    string result = SaveImage(imgBytes, imgType);

                    UpLoadBack upLoadBack = JsonConvert.DeserializeObject<UpLoadBack>(result);
                    //图片id
                    Int64 imgId = upLoadBack.ResourceID;
                    //替换为hexstudy的web路径
                    string newSrc=@"http://cms.ld.hexstudy.com/FileManage/DownLoadImage?id="+imgId;
                    content = content.Replace(src, newSrc);
                }
            }
            //throw new NotImplementedException();
        }

        [JsonObject]
        [DataContract]
        public class UpLoadBack
        {
            private long resourceID = 0;
            /// <summary>
            /// 资源ID
            /// </summary>
            [JsonProperty("ResourceID")]
            [DataMember]
            public long ResourceID
            {
                get
                {
                    return resourceID;
                }
                set
                {
                    resourceID = value;
                }
            }


            /// <summary>
            /// 资源地址
            /// </summary>
            private string path = string.Empty;
            [JsonProperty("Path")]
            [DataMember]
            public string Path
            {
                get
                {
                    return path;
                }
                set
                {
                    path = value;
                }
            }

            /// <summary>
            /// 资源所属组名
            /// </summary>
            private string group = string.Empty;
            [JsonProperty("Group")]
            [DataMember]
            public string Group
            {
                get
                {
                    return group;
                }
                set
                {
                    group = value;
                }
            }

            private string size;
            /// <summary>
            /// 资源大小
            /// </summary>
            [JsonProperty("Size")]
            [DataMember]
            public string Size
            {
                get
                {
                    return size;
                }
                set
                {
                    size = value;
                }
            }

            /// <summary>
            /// 带有组名的全文件路径
            /// </summary>
            [JsonProperty("FileName")]
            [DataMember]
            public string FileName { get; set; }

        }

        public string SaveImage(byte[] imageBytes,string imgType)
        {

            //string cms = System.Configuration.ConfigurationManager.AppSettings["cmsWebsite"];
            //if (string.IsNullOrEmpty(cms)) return null;
            //string newCms = cms.Replace("https", "http");
            //var token = HexStudy.WebCommon.Authen.Token.GetToken(CurrentUser.Name);
            string url = "http://cms.ld.hexstudy.com" + "/FileManagement/UpLoadFile_Server?ssotoken=69D9701A6E0DBC48597201653442D9E09F7CF361EDC5FC63C5D6C70EE2608CC5612E35A657D4EE05D517660D1385BB4551273C8361ECE160E484FF512D87FDA0956CF5CC977616CBE47C415061D60A6066B792C0DE00F06A1BF3835FB235735A";
            System.Net.HttpWebRequest request = System.Net.HttpWebRequest.CreateHttp(url); //System.Net.HttpWebRequest.Create(url);
            request.Method = "POST";
            request.KeepAlive = true;
            request.ContentType = "application/x-www-form-urlencoded";
            request.Headers.Add("ext", imgType);
            request.Headers.Add("contentType", "image/" + imgType);
            request.Headers.Add("hash", Guid.NewGuid().ToString());
            //填充POST数据
            request.ContentLength = imageBytes.Length;
            //myReq.
            System.IO.Stream requestStream = request.GetRequestStream();
            requestStream.Write(imageBytes, 0, imageBytes.Length);
            requestStream.Close();
            string result = string.Empty;
            try
            {
                //发送POST数据请求服务器
                System.Net.HttpWebResponse HttpWResp = (System.Net.HttpWebResponse)request.GetResponse();

                System.IO.Stream myStream = HttpWResp.GetResponseStream();

                //获取服务器返回信息
                System.IO.StreamReader reader = new System.IO.StreamReader(myStream, System.Text.Encoding.UTF8);
                result = reader.ReadToEnd();


                //释放
                myStream.Close();

            }
            catch (Exception exp)
            {
                result = "报错：" + exp.Message;
            }

            return result;
        }

        /// <summary>
        /// 获取图片的byte数组
        /// </summary>
        /// <param name="imgPath">图片路径</param>
        public byte[] GetByte(string imgPath)
        {
            FileStream fs = File.OpenRead(imgPath); //OpenRead
            int filelength = 0;
            filelength = (int)fs.Length; //获得文件长度 
            Byte[] image = new Byte[filelength]; //建立一个字节数组
            fs.Read(image, 0, filelength); //按字节流读取
            fs.Seek(0, SeekOrigin.Begin);
            //System.Drawing.Image result = System.Drawing.Image.FromStream(fs);
            fs.Close();
            return image;
            //Bitmap bit = new Bitmap(result);
        }

        /// <summary>
        /// 将流文件转换为Bypt数据
        /// </summary>
        /// <param name="stream"></param>
        /// <returns></returns>
        private byte[] SteamToBytes(Stream stream)
        {
            byte[] bytes = new byte[stream.Length];
            stream.Read(bytes, 0, bytes.Length);
            stream.Seek(0, SeekOrigin.Begin);
            return bytes;
        }

        #region 根据流的类型 判断图片的后缀名称

        /// <summary>
        /// 实现通过文件头2个字节判断图片的格式。
        /// </summary>
        public class ImageTypeCheck
        {
            static ImageTypeCheck()
            {
                _imageTag = InitImageTag();
            }

            private static SortedDictionary<int, ImageType> _imageTag;

            public static readonly string ErrType = ImageType.none.ToString();

            private static SortedDictionary<int, ImageType> InitImageTag()
            {
                SortedDictionary<int, ImageType> list = new SortedDictionary<int, ImageType>();

                list.Add((int)ImageType.bmp, ImageType.bmp);
                list.Add((int)ImageType.jpg, ImageType.jpg);
                list.Add((int)ImageType.gif, ImageType.gif);
                list.Add((int)ImageType.pcx, ImageType.pcx);
                list.Add((int)ImageType.png, ImageType.png);
                list.Add((int)ImageType.psd, ImageType.psd);
                list.Add((int)ImageType.ras, ImageType.ras);
                list.Add((int)ImageType.sgi, ImageType.sgi);
                list.Add((int)ImageType.tiff, ImageType.tiff);
                return list;

            }

            /// <summary>  
            /// 通过文件头判断图像文件的类型  
            /// </summary>  
            /// <param name="path"></param>  
            /// <returns></returns>  
            public static string CheckImageTypeName(string path)
            {
                return CheckImageType(path).ToString();
            }

            /// <summary>  
            /// 通过文件头判断图像文件的类型  
            /// </summary>  
            /// <param name="path"></param>  
            /// <returns></returns>  
            public static ImageType CheckImageType(string path)
            {
                byte[] buf = new byte[2];
                try
                {
                    using (StreamReader sr = new StreamReader(path))
                    {
                        int i = sr.BaseStream.Read(buf, 0, buf.Length);
                        if (i != buf.Length)
                        {
                            return ImageType.none;
                        }
                    }
                }
                catch (Exception exc)
                {
                    //Debug.Print(exc.ToString());
                    return ImageType.none;
                }
                return CheckImageType(buf);
            }

            public static ImageType CheckImageType(Stream stream)
            {
                byte[] buf = new byte[2];
                try
                {
                    StreamReader sr = new StreamReader(stream);
                    int i = sr.BaseStream.Read(buf, 0, buf.Length);
                    if (i != buf.Length)
                    {
                        return ImageType.none;
                    }
                }
                catch (Exception exc)
                {
                    //Debug.Print(exc.ToString());
                    return ImageType.none;
                }
                return CheckImageType(buf);
            }

            /// <summary>  
            /// 通过文件的前两个自己判断图像类型  
            /// </summary>  
            /// <param name="buf">至少2个字节</param>  
            /// <returns></returns>  
            public static ImageType CheckImageType(byte[] buf)
            {
                if (buf == null || buf.Length < 2)
                {
                    return ImageType.none;
                }

                int key = (buf[1] << 8) + buf[0];
                ImageType s;
                if (_imageTag.TryGetValue(key, out s))
                {
                    return s;
                }
                return ImageType.none;
            }

        }

        /// <summary>  
        /// 图像文件的类型  
        /// </summary>  
        public enum ImageType
        {
            none = 0,
            bmp = 0x4D42,
            jpg = 0xD8FF,
            gif = 0x4947,
            pcx = 0x050A,
            png = 0x5089,
            psd = 0x4238,
            ras = 0xA659,
            sgi = 0xDA01,
            tiff = 0x4949
        }

        #endregion
    }
}
